//
//  MineDetailVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/22.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "MineDetailVC.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "LoginViewController.h"


#import "QiniuSDK.h"
#import "ZHPickView.h"
#import <AssetsLibrary/AssetsLibrary.h>//相册权限
#import <AVFoundation/AVCaptureDevice.h>//相机权限
#import <AVFoundation/AVMediaFormat.h>

@interface MineDetailVC ()
<
    UITextFieldDelegate,
    UINavigationControllerDelegate,
    UIImagePickerControllerDelegate,
    UIGestureRecognizerDelegate,
    ZHPickViewDelegate
>
{
    
    UILabel * nameLabel;
    UILabel * phoneLbel;
    UILabel * emailLbel;
    
}
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIImageView *imagev;

@property (nonatomic, strong) ZHPickView *pickV;


@property (nonatomic, strong) UIView *dateView;
@property (nonatomic, strong) UIDatePicker *datePicker;

@property (nonatomic, assign) int currentTextFieldIndex;

@property (nonatomic, strong) NSMutableDictionary *dataDictionary;


@property (nonatomic,copy) NSString *token;
@property (nonatomic,copy) NSString *qiNiuKey;



@property (nonatomic, strong) TopBackView *topBackView;
@end

@implementation MineDetailVC

#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView) {
        
        CGRect frame = CGRectMake(0, 0, screenWidth, 64);
        
        _topBackView = [[TopBackView alloc]initViewWithFrame:frame andTitle:@"编辑资料"];
        
        [_topBackView.rightButton setTitle:@"保存" forState:UIControlStateNormal];
        
        _topBackView.rightButton.titleLabel.font = Font(14);
       
        [_topBackView.rightButton setTitleColor:WhiteColor forState:UIControlStateNormal];
        
    
        [_topBackView.rightButton addTarget:self
                                     action:@selector(naviRightItemClick)
                           forControlEvents:UIControlEventTouchUpInside];
        
        
        [_topBackView.leftButton addTarget:self
                                    action:@selector(naviLeftItemClick)
                          forControlEvents:UIControlEventTouchUpInside];

    }
    return _topBackView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
       _scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    }
    return _scrollView;
}


#pragma mark -
#pragma mark - 初始化视图
- (void)viewDidLoad {
    [super viewDidLoad];
    
    ///设置本地数据配置
    [self setUpLocalData];
    
    ///设置UI
    [self setUpUI];
   
    ///获取服务器数据
    [self getServerData];
 
    [self initSubviews];
    

    ///添加观察者
    [self addMangerObserver];
}

#pragma mark - 设置UI
- (void)setUpUI {
 
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topBackView];
    [self.view addSubview:self.scrollView];
}

#pragma mark - 设置本地数据配置
- (void)setUpLocalData {
    self.qiNiuKey = @"";
    self.dataDictionary = [NSMutableDictionary dictionary];
    
}

- (void)initSubviews{
    
    
    /// 头像视图
    UIView *pictureView = [self backViewWithFrame:CGRectMake(0, 0, screenWidth, 78) andString:@""];
 
    self.imagev = [[UIImageView alloc] initWithFrame:CGRectMake(20, 14, 50, 50)];
    self.imagev.layer.cornerRadius = 25;
    self.imagev.layer.masksToBounds = YES;
    [pictureView addSubview:self.imagev];
    [self.scrollView addSubview:pictureView];
    
    
    
    // 用户名
    UIView *nameView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(pictureView.frame) + 10, screenWidth, cellHeight) andString:@"姓名"];
    [self.scrollView addSubview:nameView];
    self.scrollView.backgroundColor = GrayColor;
    
    nameLabel = [UILabel createUIlabel:@"姓名" andFont:FontOfSize13 andColor:littleBlackColor];
    [self.scrollView addSubview:nameLabel];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(nameView.mas_right).with.offset(-10*kWidth);
        make.centerY.equalTo(nameView.mas_centerY);
    }];

    
    //手机号

    UIView *genderView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(nameView.frame), screenWidth, cellHeight) andString:@"手机号"];
    [self.scrollView addSubview:genderView];
    phoneLbel = [UILabel createUIlabel:@"手机号" andFont:FontOfSize13 andColor:littleBlackColor];
    [self.scrollView addSubview:phoneLbel];
    [phoneLbel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(genderView.mas_right).with.offset(-10*kWidth);
        make.centerY.equalTo(genderView.mas_centerY);
    }];
    
    //邮箱
    UIView *emailView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(genderView.frame), screenWidth, cellHeight) andString:@"邮箱"];
    [self.scrollView addSubview:emailView];
    
    emailLbel = [UILabel createUIlabel:@"邮箱" andFont:FontOfSize13 andColor:littleBlackColor];

    [self.scrollView addSubview:emailLbel];
    [emailLbel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(emailView.mas_right).with.offset(-10*kWidth);
        make.centerY.equalTo(emailView.mas_centerY);
    }];

    
    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    logoutButton.backgroundColor = WhiteColor;
    logoutButton.frame = CGRectMake(0, CGRectGetMaxY(emailView.frame) + 10, screenWidth - 0, cellHeight);
    [logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
    //    logoutButton.layer.cornerRadius = 5;
    logoutButton.titleLabel.font = Font(13);
    [logoutButton addTarget:self action:@selector(logoutButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [logoutButton setTitleColor:YellowColor forState:UIControlStateNormal];
    
    [self.scrollView addSubview:logoutButton];

}

#pragma mark - 获取服务器数据
- (void)getServerData{
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    __weak typeof(self) weakSelf = self;
    
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
        
       [WKProgressHUD dismissInView:weakSelf.view animated:YES];

        if ([responseObj[@"success"] boolValue]) {
            
            self.dataDictionary = responseObj[@"data"];
            //赋值
            [self getValueString];
        }
        else
        {
            [WKProgressHUD popMessage:responseObj[@"message"] inView:weakSelf.view duration:1.5 animated:YES];

        }
        
    } failed:^(NSString *errorMsg) {
        
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        NSLog(@"%@",errorMsg);
    }];
}

- (void)getValueString{
    
    
    
//    data =     {
//        addr = "<null>";
//        email = "123@123.com";
//        enable = 1;
//        id = 1;
//        loginName = 15210491697;
//        phone = 15210491697;
//        picKey = FqePDQkCjcnkuhxf2WbOtv8YiIsi;
//        picUrl = "http://qiniu.test.huiyunche.cn/FqePDQkCjcnkuhxf2WbOtv8YiIsi?e=1497500047&token=wQknukoe-lwcjLKEnsBz-BrL61M1BEMP0Gq_M2qP:DA4ht-0Vqvb67Ik9bQoDI0E3IJY=";
//        realName = "\U5019\U5efa\U6167";
//        saleCompanyDivisionId = 1;
//        saleCompanyId = 1;
//        type = 10;
//        userStatus = 10;
//    };

    
    if ([self.dataDictionary[@"pic"] isEqual:[NSNull null]])
    {
        self.imagev.image = [UIImage imageNamed:@"image_1"];
    }
    else
    {
        //拼接图片url
        NSString *urlString = [NSString stringWithFormat:@"%@",self.dataDictionary[@"picUrl"]];
        
        [self.imagev sd_setImageWithURL:[NSURL URLWithString:urlString]
                       placeholderImage:[UIImage imageNamed:@"image_1"]];
    }
    
    nameLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"realName"]];
    phoneLbel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"phone"]];
    emailLbel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"email"]];

}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    [rootVC setTabBarHidden:YES];
}

#pragma mark 退出登录
- (void)logoutButtonAction{
   
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    __weak typeof(self) weakSelf = self;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController *loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        [weakSelf presentViewController:loginNC animated:YES completion:nil];
        
        [userDefaults setObject:nil forKey:@"login"];
        [userDefaults setObject:nil forKey:@"phone"];
        [userDefaults setObject:nil forKey:login_token];
        [userDefaults setObject:nil forKey:@"userType"];
        
    });
    
}


#pragma mark 从七牛获取Token
- (void)getTokenFromQN{
    
    [Common requestWithUrlString:picture_qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            [self uploadImageToQNWithData:[self getImageWith:self.imagev.image]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

- (void)uploadImageToQNWithData:(NSData *)data{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
       [WKProgressHUD dismissInView:self.view animated:YES];
        
        self.qiNiuKey = resp[@"key"];
        
    } option:uploadOption];
}

- (NSData *)getImageWith:(UIImage *)image{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        data = UIImageJPEGRepresentation(image, 0.2);
    } else {
        data = UIImagePNGRepresentation(image);
    }
    return data;
}

#pragma mark -
#pragma mark - 添加观察者
- (void)addMangerObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popSelf) name:@"dismiss" object:nil];
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"dismiss" object:nil];
}
- (void)popSelf{
    [self .navigationController popViewControllerAnimated:NO];
}

#pragma mark -
#pragma mark - 导航栏点击
#pragma mark -

#pragma mark - 返回
- (void)naviLeftItemClick {
    
    [self.pickV removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, frame.size.height/2 - 10, 100, 20)];
    label.text = string;
    label.font = Font(13);
    label.textColor = littleBlackColor;
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0,frame.size.height - 0.5, self.view.frame.size.width , 0.5)];
    label1.backgroundColor = [UIColor colorWithRed:205/255.0 green:205/255.0 blue:205/255.0 alpha:1];
    [view addSubview:label1];
    
    //    [view addSubview:imageV];
    [view addSubview:label];
    return  view;
}

@end
